//弹出层表头悬停
//$(window).scroll(onScroll);


/**
 * 初始化时间控件
 * @param startView
 * @param reportId
 */
function initeDatetimepicker(startView,reportId) {
	// 定义延迟对象
	var dtd = $.Deferred();
	if(!startView) {
		startView = 3 ;
	}
	// 日历设置及初始化
	$("#"+tabId+" #date_div").bind("mouseover", opc1);
	$("#"+tabId+' #date_div').bind('mouseout', opc0);
	$('#'+tabId+ " #sdate").datetimepicker({
	    format: "yyyy-mm-dd",
	    autoclose: true,
	    todayBtn: true,
	    minView: 2,
	    startView:startView,
	    language: 'zh-CN'
	});
	$('#'+tabId+" #edate").datetimepicker({
	    format: "yyyy-mm-dd",
	    autoclose: true,
	    todayBtn: true,
	    minView: 2,
	    startView:startView,
	    language: 'zh-CN',
	});
	$('#'+tabId+" #qdate").datetimepicker({
	    format: "yyyy-mm",
	    autoclose: true,
	    todayBtn: true,
	    minView: 2,
	    startView: 'year',
        minView:'year',
        maxView:'decade',
	    language: 'zh-CN',
	});
	$("#"+tabId+" #sdate").datetimepicker().on('show', function(ev){
		$('#'+tabId+' #date_div').unbind();
	});
	$("#"+tabId+" #sdate").datetimepicker().on('hide', function(ev){
		$('#'+tabId+' #date_div').bind('mouseover', opc1);
		$('#'+tabId+' #date_div').bind('mouseout', opc0);
	});
	$("#"+tabId+" #edate").datetimepicker().on('show', function(ev){
		$('#'+tabId+' #date_div').unbind();
	});
	$("#"+tabId+" #edate").datetimepicker().on('hide', function(ev){
		$('#'+tabId+' #date_div').bind('mouseover', opc1);
		$('#'+tabId+' #date_div').bind('mouseout', opc0);
	});
	$("#"+tabId+" #qdate").datetimepicker().on('show', function(ev){
		$('#'+tabId+' #date_div').unbind();
	});
	$("#"+tabId+" #qdate").datetimepicker().on('hide', function(ev){
		$('#'+tabId+' #date_div').bind('mouseover', opc1);
		$('#'+tabId+' #date_div').bind('mouseout', opc0);
	});
	
	$.ajax({
		url:contextPath + "/Report/initeDateTimePicker.dhc",
		async:false,
		type:"post",
		dataType:"json",
		success:function(data){
			var date = data.data
			// 获取该月份的开始日期和结束日期
			if(date) {
				// 病例日分析默认显示最新一天的
				if("caseDayAnalysis_all" == reportId) {
					$('#'+tabId+' #sdate').val(date.lastDate);
					$('#'+tabId+' #edate').val(date.lastDate);
				} else {
					$('#'+tabId+' #sdate').val(date.startDateMonth);
					$('#'+tabId+' #edate').val(date.lastDate);
					$('#'+tabId+' #qdate').val(date.startDateMonth.substr(0,7));
				}
			}else{
				$('#'+tabId+' #sdate').val(GetDateStr(0,'d'));
				$('#'+tabId+' #edate').val(GetDateStr(0,'d'));
				$('#'+tabId+' #qdate').val(GetDateStr(0,'m'));
			}
			// 将延迟对象改为完成状态
			dtd.resolve();
		}
	})
	// 此时的dtd对象为 未完成状态
	return dtd.promise();
}

/**
 * 获取MDC编码及名称
 */
function getAllMdc(){
	// 定义延迟对象
	var dtd = $.Deferred();
	$.post(contextPath +"/MDCGroup/findAllMDC.dhc",{"verCode":sysConfig.GROUP_VER}).done(function(result) {
		var data = result.data;
		var optStr = "";
        for(var i = 0;i<data.length;i++) {
            if(i==0) {
                optStr = optStr + '<option value="'+data[i].MDC_CODE+'" selected="selected">'+data[i].MDC_CODE+'-'+data[i].MDC_DESC+'</option>';
            } else {
                optStr = optStr + '<option value="'+data[i].MDC_CODE+'">'+data[i].MDC_CODE+'-'+data[i].MDC_DESC+'</option>';
            }
        }
		//多选下拉框初始化
		$("#"+tabId+" #mdcCode").append(optStr);
		$("#"+tabId+" .multiselect").multiselect({
			includeSelectAllOption: true  ,
			selectAllText: '全部选择' ,
			allSelectedText: '全部选择'
		});
		$("#"+tabId+" #mdcCode").next(".btn-group").width(200);
		$("#"+tabId+" #mdcCode").next(".btn-group").find("button").width(200);
		// 将延迟对象改为完成状态
		dtd.resolve();
	})
	// 此时的dtd对象为 未完成状态
	return dtd.promise();
}

// 获取当前登录用户的信息
function getCurrentUserInfo(roleId,reportType,reportId) {
	var url = "" ;
	if(roleId == "depCode"){
		 url = contextPath+'/DepDisMonitor/getUserInfo.dhc' ;
	} else if (roleId == "wardCodes"){
		 url = contextPath+'/wardMonitor/getUserInfo.dhc' ;
	}
	$.ajax({
		url: url,
		async:false,
		type: 'POST',
		dataType:"json",
		success:function(userInfo) {
			var roleCode = "" ;
			// 科室角色
			if(userInfo.data != "undefined" && userInfo.data != null ){
				roleCode = userInfo.data.depCode;
				if(roleCode == null) {
					alert("没有为该用户授权科室") ;
				}
			} else { // 病区角色
				roleCode = userInfo.wardCode;
			}
			$("#"+tabId+" #"+roleId).val(roleCode) ;
			showReport(reportType,reportId) ;
		}
	});
}


/**
 * 获取所有科室组信息
 */
function getAllDepGroup() {
	//获取所有科室组列表
	var dtd = $.post(contextPath+'/DrgsIndexCal/getDepGroupByCode.dhc', {
		'hospCode': paramTabPage[tabId].hospCode,'depGroupCode': '', 'depCode':'',  'wardCode':'' }).done(function(result) {
			var data = result.data;
			var optStr = "";
			for(var i = 0;i<data.length;i++) {
				if(i==0) {
					optStr = optStr + '<option value="'+data[i].depGroupCode+'" selected="selected">'+data[i].depGroupDesc+'</option>';
				} else {
					optStr = optStr + '<option value="'+data[i].depGroupCode+'">'+data[i].depGroupDesc+'</option>';
				}
			}
			//多选下拉框初始化
			$("#"+tabId+" #depGroupCode").append(optStr);
			$("#"+tabId+" .multiselect").multiselect({
				includeSelectAllOption: true ,
				selectAllText: '全部选择' ,
				allSelectedText: '全部选择'
			});
		})
	return dtd ;
}

/**
 * 获取所有科室信息
 */
function getAllDep(selectId) {
	// 定义延迟对象
	var param=drgUI.setAjaxData(tabId);
	//获取所有科室列表
	var dtd = $.post(contextPath+'/DrgsIndexCal/findAllDepByHospCode.dhc', param).done(function(result) {
		var data = result.data;
		var optStr = "";
		for(var i = 0;i<data.length;i++){
			if(i==0) {
				optStr = optStr + '<option value="'+data[i].depCode+'" selected="selected">'+data[i].depName+'</option>';
			}
			else {
				optStr = optStr + '<option value="'+data[i].depCode+'">'+data[i].depName+'</option>';
			}
		}
		//多选下拉框初始化
		$("#"+tabId+" #"+selectId+"").append(optStr);
		$("#"+tabId+" .multiselect").multiselect({
			includeSelectAllOption: true  ,
			selectAllText: '全选选择' ,
			allSelectedText: '全部选择'
		});
	});
	return dtd ;
}



/**
 * 获取所有病区信息
 */
function getAllWard(selectId) {
	//获取病区数据
	var dtd = $.post(contextPath+'/DrgsIndexCal/getWardByCode.dhc', {
		'hospCode': paramTabPage[tabId].hospCode,
		'depGroupCode': '',
		'depCode':'', 
		'wardCode':''
	}).done(function(result) {
		 if(result.success ){
			 var wardAll = result.data;
			 	var optStr = "";
				 for(var i = 0;i<wardAll.length;i++) {
						if(i==0) {
							optStr = optStr + '<option value="'+wardAll[i].wardCode+'" selected="selected">'+wardAll[i].wardDesc+'</option>';
						}
						else {
							optStr = optStr + '<option value="'+wardAll[i].wardCode+'">'+wardAll[i].wardDesc+'</option>';
						}
				}
				//多选下拉框初始化
				$("#"+tabId+" #"+selectId+"").append(optStr);
				$("#"+tabId+" .multiselect").multiselect({
					includeSelectAllOption: true  ,
					selectAllText: '全选选择' ,
					allSelectedText: '全部选择'
				});
		 }
		 $("#"+tabId+" #ward_name").next(".btn-group").width(200);
		 $("#"+tabId+" #ward_name").next(".btn-group").find("button").width(200);
	 });
	return dtd ;
}


/**
 * 获取外院比较信息
 */
function getOtherHosp() {
    // 定义延迟对象
    var dtd = $.Deferred();
    //获取所有外院比较对象代码名称及标杆年份
    $.ajax({
        url : contextPath + "/Report/getOtherHspManage.dhc",
        type : "post",
        dataType : "json",
        async : false,
        success : function(result) {
            var data = result.data;
            var optStrCode = "";
            if(data.length>0){
                var notDescStr="请在字典管理配置字典编码为STD_TARGET,以下字典值为空：";
                // 是否提示
                var flag = false ;
                for(var i = 0;i<data.length;i++) {
                    // 编码进行字典映射
                    var arrayDic = array_filter(diction.STD_TARGET, "DICVALUE", [data[i].MS_CODE]) ;
                    var desc = "未配置" ;
                    if(arrayDic.length>0 && arrayDic[0].DICDESC) {
                        desc = arrayDic[0].DICDESC
                        if(i==0) {
                            optStrCode = optStrCode + '<option value="'+data[i].MS_CODE+'" selected="selected">'+desc+'</option>';
                        } else {
                            optStrCode = optStrCode + '<option value="'+data[i].MS_CODE+'">'+desc+'</option>';
                        }
                    } else {
                        notDescStr+=data[i].MS_CODE+",";
                        flag = true ;
                    }
                }
                if(flag) {
                    drgUI.alert(notDescStr);
                }
            } else {
                optStrCode = optStrCode + '<option value="0">无数据</option>';
            }
            //下拉框初始化
            $("#"+tabId+" #stdCode").append(optStrCode);
            // 将延迟对象改为完成状态
            dtd.resolve();
        }
    });
    // 此时的dtd对象为 未完成状态
    return dtd.promise();
}


/**
 * 获取所有外院比较对象代码名称及标杆年份
 * @@param parMsCode
 * @void
 * @ Discription:
 * @common.js
 */
function getOtherHspManageYears(parMsCode) {
	//获取所有外院比较对象代码名称及标杆年份
	$.ajax({
		url : contextPath + "/Report/getOtherHspManageYears.dhc",
		type : "post",
		dataType : "json",
//		async : false,
		data:{"parMsCode":parMsCode} ,
		success : function(result) {
			var data = result.data;
			var optStrCode = "";
			if(data.length > 0) {
				for(var i = 0;i<data.length;i++)
				{
					if(i==0)
					{
						optStrCode = optStrCode + '<option value="'+data[i]+'" selected="selected">'+data[i]+'</option>';
					}
					else
					{
						optStrCode = optStrCode + '<option value="'+data[i]+'">'+data[i]+'</option>';
					}
				}
			} else {
				optStrCode = optStrCode + '<option value="0">无数据</option>';
			}
			
			//下拉框初始化
			$("#"+tabId+" #stdYear").append(optStrCode);
		}
	});
}

//展开日期标杆
function opc1(){
	if ($('#'+tabId+' #date_div').css('position')=='fixed') {
		$('#'+tabId+' #date_div').removeClass("hoverOut").addClass("hoverIn");
	}
}
//收起日期标杆
function opc0(){
	if ($('#'+tabId+' #date_div').css('position')=='fixed') {
		$('#'+tabId+' #date_div').removeClass("hoverIn").addClass("hoverOut");
	}
}

// 导出按钮特效
$('#exportType a').mouseover(function(e) {
    $(this).siblings().stop().fadeTo(200,0.4);
});

$('#exportType a').mouseout(function(e) {
    $(this).siblings().stop().fadeTo(200,1);
});

// 查询条件
/**
 * inCondition in后面的条件 如 drgCode in ("MDCA,MDCB")
 */
var inCondition = ["mdcCode","depGroupCode","depCode","wardCode","pargroupName"] ;
/**
 * commonCondition 普通的字符串条件 
 */
var commonCondition = ["qdate","sdate","edate","stdCode","stdYear","depCodes","wardCodes","pargroupNames","dateField"] ;

var lastParam = '';
var rIds = {};
/**
 * 
 * @@param reportType 文件格式
 * @@param reportId  报表id
 * @@param isLazyLoad 是否重复加载
 * @@param btn 查询按钮
 * @@param isDatatable 是否使用datatable预览
 * @void
 * @ Discription:
 * @common.js
 */
function showReport(reportType,reportId,isLazyLoad,btn,isDatatable) {
	// 获取报表div
	var reportDiv = $('#'+tabId+ ' #' + reportId + 'Div') ;
	if(reportDiv.length == 0 ){
		reportDiv = $('#'+tabId+' #reportDiv') ;
	}
	var param = {} ;
	// 院区编码
	param.hospCode = paramTabPage[tabId].hospCode ;
	
	// 普通条件 （非in条件）
	for(var i in commonCondition){
		if( $("#"+tabId+" #"+commonCondition[i]+"").length > 0) {
			param[commonCondition[i]] =  $("#"+tabId+" #"+commonCondition[i]+"").val();
		}
	}
	// 带in条件的参数
	for(var i in inCondition){
		if( $("#"+tabId+" #"+inCondition[i]+"").length > 0){
			var str = $("#"+tabId+" #"+inCondition[i]+"").val()+"" ;
			if(""== str){
				break ;
			}
			param[inCondition[i]+"s"] =  str ;
			param[inCondition[i]] = param[inCondition[i]+"s"].split(",") ;
		}
	}
	//查询条件无更改时切换页签不用重复查询
	if(arguments[3]=='btn'){
		rIds = {};
	}
	rIds[reportId] = reportId;
	param['reportId'] = rIds ;
	if(isLazyLoad && lastParam == JSON.stringify(param)){
		return ;
	} else {
		lastParam = JSON.stringify(param);
	}
	// 医政角色下的科室组 科室 病区 主诊组 报表SQL需要从数据库查询
	if(reportId == "depgroup" || reportId == "dep" || reportId == "ward" || reportId == "pargroup"){
		param.sql = "oracle" ;
	}
	// 页面预览
	if(reportType == "html"){
		// 使用datatable 预览
		if(isDatatable){
			return previewInDatatable(param,reportId,reportId)  ;
		}
//		iframe.src=contextPath+'/Report/exreport.dhc?param='+JSON.stringify(param)+'&reportType='+reportType+'&reportId='+reportId ;
		// html预览
		if(reportDiv != null || reportDiv != undefined ){
			 $.ajax({
	             type: "post",
	             url: contextPath+"/Report/exreportPMode.dhc",
	             data: {param: JSON.stringify(param),reportType:reportType ,reportId:reportId },
	             dataType: "html" ,
	             success:function(data){
	            	 reportDiv.html(data) ;
	//	            	 reportDiv.find("div").css({"display":"inline","text-align:center":""}) ;
	//	            	 reportDiv.find("div").parents("td").css({"vertical-align":"middle","text-align":"center"}) ;
	            	 
	             }
	          })
		}
	} else {
		// 导出文件
		var form = $("<form></form>") ;
		form.attr("action",contextPath + "/Report/exreportPMode.dhc" ) ;
		form.attr("method","POST") ;
//		form.attr('target', '_self');
		var $param = $('<input type="hidden" name="param"/>');
		var param= JSON.stringify(param) ;
		$param.attr("value",param) ;
		var $reportType = $('<input type="hidden" name="reportType"/>');
		$reportType.attr("value",reportType) ;
		var $reportId = $('<input type="hidden" name="reportId" />');
		$reportId.attr("value",reportId) ;
		form.append($param,$reportType,$reportId);
		$(document.body).append(form);
		form.submit() ;
	}
}

/**
 * 使用datatable 进行预览
 * @@param param
 * @@param reportId
 * @@param reportDiv
 * @void
 * @ Discription:
 * @common.js
 */
function previewInDatatable(param,reportId,reportId) {
	$.ajax({
        type: "post",
        url: contextPath+"/Report/previewInDatatable.dhc",
        data: {param: JSON.stringify(param),reportId:reportId },
        success:function(data){
       	 var columns=[
		               	{"data": "rowNum","title": "序号",
		               		"render":function(data,type,full,meta){
		               			return meta.row+1 ;
		               		}
		               	},
		               	{"data": "MR_NO","title":"病案号",
		               		"render":function(data,type,full,meta){
		               			return "<a href=\"javascript:medicalRecordJasper('"+full.PMAININDEX+"','"+full.PATIENT_NAME+"')\">"+full.MR_NO+"</a>" ;
		               		}
		               	},
		               	{"data": "PARDRG_CODE","title":"DRG代码" },
		               	{"data": "DRG_DESC","title":"DRG描述" },
		               	{"data": "OUT_DATE","title":"出院时间"},
		               	{"data": "OUT_DEP","title":"出院科室" },
		               	{"data": "RISKLEVEL","title":"风险等级" },  // 6
		           		{"data": "COSTAMOUNT","title":"住院总费用"} ,
		           		{"data": "AS_AVG_FEE","title":"病组费用标杆"}, // 8
		           		{"data": "IN_DAYS","title":"住院天数"},
		           		{"data": "OVERFEERATIO","title":"费用超标率(%)"}, // 10
		           		{"data": "OVERDAYSRATIO","title":"平均住院日超标率(%)"}, //11
		           		{"data": "AS_AVG_DAYS","title":"病组住院日标杆"}, //12
		           		{"data": "AS_WEIGHT","title":"病组权重"}, //13
		           		{"data": "PATIENT_NAME","title":"姓名"},
		           		{"data": "AGE_YEAR","title":"年龄"},
		           		{"data": "IN_DATE","title":"入院时间"},
		           		{"data": "IN_DEP","title":"入院科室"},
		           		{"data": "OUT_WAY","title":"离院方式"},
		           		{"data": "OP_DIAGNOSIS","title":"门急诊诊断编码及诊断描述"},
		           		{"data": "DIAGNOSE","title":"诊断编码及诊断描述",
		               		"render":function(data,type,full,meta){
		               			return linefeedText(data);
		               		} 
		           		}, //20
		           		{"data": "OPERATION","title":"手术编码及手术名称",
		               		"render":function(data,type,full,meta){
		               			return linefeedText(data);
		               		}
		           		}, //21
		           		{"data": "NOTIN_REASON","title":"未入组原因"},
		           		{"data": "DEP_MASTER","title":"科主任"},
		           		{"data": "PROTOMEDICUS","title":"主任医师"},
		           		{"data": "PHYSICIAN","title":"主治医师"}
		           	];
       	var columnDefs = [] ;
       	// 大于60天和未入组的不展示DRG信息
       	if(reportId == "caseDayAnalysis_notInGroup" ) {
       		columnDefs.push({ "visible": false, "targets": [2,3,6,8,12,13] }) ;
       	} else if (reportId == "caseDayAnalysis_gl60") {
       		columnDefs.push({ "visible": false, "targets": [2,3,6,8,12,13,22]}) ;
       	} else if (reportId == "caseDayAnalysis_dead") { // 死亡病例显示风险等级列
       		columnDefs.push({ "visible": false, "targets": [22]}) ;
       	} else {
       	// 入组的(除死亡病例外)不展示未入组原因列 和 风险等级列
       		columnDefs.push({ "visible": false, "targets": [6,22] }) ;
       	}
     	var paramsDataTables={searching:true,lengthChange:true,ordering:true,stateSave:false,scrollX:true,scrollY:'350px',autoWidth:false,orderCellsTop:true,tableTitle: "病例明细" ,columnDefs:columnDefs};
     	paramsDataTables.dom = '<"top"fl>rt<"bottom"ip><"clear">' ;

     	var reportDiv = $('#'+tabId+ ' #' + reportId + 'Div') ;
     	reportDiv.dataTableBasic(columns,data.data.detail,paramsDataTables) ;
     	if(data.data.total) {
     		var info = "<h5>当期共处理"+formatNumJasper(data.data.total[0].TOTALCASE,0)+"例病例，其中DRG入组病例"+formatNumJasper(data.data.total[0].INCASE,0)+"例，未入组病例"+formatNumJasper(data.data.total[0].NOTINCASE,0)+"例，大于60天病例"+formatNumJasper(data.data.total[0].DAY60,0)+"例，费用超标病例"+formatNumJasper(data.data.total[0].FEEOVER,0)+"例，住院日超标病例"+formatNumJasper(data.data.total[0].INDAYOVER,0)+"例，费用和住院日均超标病例"+formatNumJasper(data.data.total[0].ALLOVER,0)+"例，死亡病例"+formatNumJasper(data.data.total[0].DEADCASE,0)+"例，低风险死亡"+formatNumJasper(data.data.total[0].RISK1DEADCASE,0)+"例，中低风险死亡"+formatNumJasper(data.data.total[0].RISK2DEADCASE,0)+"例。</h5>"
     		$('#'+tabId+ ' #totalCase').html(info) ;
     	}
      }
   })
}

/**
 *  打开病案首页
 * @@param id 主键
 * @@param patientName 病人姓名
 * @void
 * @ Discription:
 * @common.js
 */
function medicalRecordJasper(id,patientName){
	var tid=id.replace('.','');
	openTab('/pages/yizheng/qcPatientList.jsp',patientName+'|病案首页', 'patient'+tid,'patient'+tid,{patientId:id});
}


/**
 * 格式化方法
 * @@param num
 * @@param decimal
 * @@returns
 * @any
 * @ Discription:
 * @keyDiseaseGroupCommon.js
 */
function formatNumJasper(num,decimal) {
	if(!num || isNaN(num)) {
		if(isNaN(decimal)) {
			return decimal ;
		} else {
			return formatNumber("0",decimal) ;
		}
	} 
	return formatNumber(num,decimal)
}

/**
 *  初始化报表选择条件树
 * @@param chkStyle 单选(radio)/多选
 * @@param layer 层级 科室/病区
 * @void
 * @ Discription:
 * @common.js
 */
function initConditionZtree(layer,chkStyle,authorized) {
	var setting = {
			check: {
				enable: true,
				chkboxType:  { "Y" : "ps", "N" : "ps" }
			},
			
			view: {
				dblClickExpand: false ,
				showIcon: false
			},
			data:{
	             simpleData:{
	         	 enable: true,
	         	 idKey:  "id",
	         	 pIdKey: "pid",
	         	 rootPId:"0"
	            }  
	        } ,
			callback: {
				beforeClick: beforeClick,
				onCheck: onCheck
			}
	};
	
	if(chkStyle == "radio") {
		setting.check = {
			enable: true,
			chkStyle: "radio",
			radioType: "all",
			chkboxType: {"Y":"", "N":""}
		} 
	}
	
	$.ajax({
		url : contextPath + "/Report/queryDepTree.dhc",
		type : "post",
		dataType : "json",
		async : false,
		data:{"chkStyle":chkStyle,"layer":layer} ,
		success : function(data) {
			 var ztreenode=data.data ;
            if(authorized) {
                ztreenode = array_filter(ztreenode,"id",authorized) ;
                ztreenode[0].checked = true ;
            }
			 if(layer=="ward") {
				 var zTree = $.fn.zTree.init($("#"+tabId+" #treeWard"), setting, ztreenode);
				 var checkedNodes = zTree.getCheckedNodes(true) ;
				 var wardCode = [] ;
				 
				 if(checkedNodes.length>0){
					 wardCode.push(checkedNodes[checkedNodes.length-1].id)
					 $("#"+tabId+ " #wardCode").attr("value", wardCode);
					 $("#"+tabId+ " #wardName").attr("value", checkedNodes[checkedNodes.length-1].name);
				 }
				 $("#"+tabId+" #wardCode").next(".btn-group").width(200);
				 $("#"+tabId+" #wardCode").next(".btn-group").find("button").width(200);
			 } else {
				 var zTree = $.fn.zTree.init($("#"+tabId+" #treeDep"), setting, ztreenode);
				 var checkedNodes = zTree.getCheckedNodes(true) ;
				 var depCode = [] ;
				 if(checkedNodes.length>0){
					 depCode.push(checkedNodes[checkedNodes.length-1].id)
					 $("#"+tabId+ " #depCode").attr("value", depCode);
					 $("#"+tabId+ " #depName").attr("value", checkedNodes[checkedNodes.length-1].name);
				 } 
				 $("#"+tabId+" #depCode").next(".btn-group").width(200);
				 $("#"+tabId+" #depCode").next(".btn-group").find("button").width(200);
			 }
		}
	});
	/**
	 * 用于捕获单击节点之前的事件回调函数，并且根据返回值确定是否允许单击操作
	 */
	function beforeClick(treeId, treeNode) {
		var zTree = null ;
		if(layer=="ward") {
			zTree = $.fn.zTree.getZTreeObj("treeWard");
		} else if(layer=="dep") {
			zTree = $.fn.zTree.getZTreeObj("treeDep");
		}
		// treeNode：需要勾选 或 取消勾选 的节点数据
		// !treeNode.checked：checked = true 表示勾选节点,省略此参数，则根据对此节点的勾选状态进行 toggle 切换
		// null 表示按照 setting.check.chkboxType 属性进行父子节点的勾选联动操作。checkTypeFlag = false 且 treeNode.checked = checked 时，不会触发回调函数，直接返回
		// true 表示执行此方法时触发 beforeCheck & onCheck 事件回调函数
		zTree.checkNode(treeNode, !treeNode.checked, null, true);
		return false;
	}
	
	/**
	 * 选择节点时的事件
	 */
	function onCheck(e, treeId, treeNode) {
		if(layer == "dep") {
			onCheckDep(e, treeId, treeNode);
		} else if(layer == "ward") {
			onCheckWard(e, treeId, treeNode);
		}
		
	}

// 科室树
function onCheckDep(e, treeId, treeNode) {
	var zTree = $.fn.zTree.getZTreeObj("treeDep"),
	nodes = zTree.getCheckedNodes(true),
	v = "";
	// 统计选中的科室
	var cnt = 0 ;
	// 记录科室编码
	var depCode = [] ;
	// 判断层级
	var maxLevel = 1 ;
	if(commonLayerConfig[0] == "1"){
		maxLevel++ ;
	}
	if(chkStyle == "radio") {
		$("#"+tabId+ " #depName").attr("value", nodes[0].name);
		$("#"+tabId+ " #depCode").attr("value", nodes[0].id);
	} else {
			for (var i=0, l=nodes.length; i<l; i++) {
				if(nodes[i].level == maxLevel) {
					v += nodes[i].name + ",";
					depCode.push(nodes[i].id) ;
					cnt ++ ;
				}
			}
			if (v.length > 0 ) v = v.substring(0, v.length-1);
			var depObj = $("#"+tabId+ " #depName") ;
			if (cnt > 2) {
				depObj.attr("value", "选中"+cnt+"个");
			} else {
				depObj.attr("value", v);
			}
			$("#"+tabId+ " #depCode").attr("value", depCode);
		}
	}

	//病区树
	function onCheckWard(e, treeId, treeNode) {
		var zTree = $.fn.zTree.getZTreeObj("treeWard"),
		nodes = zTree.getCheckedNodes(true),
		v = "";
		// 统计选中的病区
		var cnt = 0 ;
		// 记录病区编码
		var wardCode = [] ;
		// 判断层级
		var maxLevel = 1 ;
		if(commonLayerConfig[0] == "1"){
			maxLevel++ ;
		}
		if(commonLayerConfig[1] == "1"){
			maxLevel++ ;
		}
		for (var i=0, l=nodes.length; i<l; i++) {
			if(nodes[i].level == maxLevel) {
				v += nodes[i].name + ",";
				wardCode.push(nodes[i].id) ;
				cnt ++ ;
			}
		}
		if (v.length > 0 ) v = v.substring(0, v.length-1);
		var wardObj = $("#"+tabId+ " #wardName") ;
		if (cnt > 2) {
			wardObj.attr("value", "选中"+cnt+"个");
		} else {
			wardObj.attr("value", v);
		}
		$("#"+tabId+ " #wardCode").attr("value", wardCode);
	}
}

/**
 * 科室选择菜单
 * @param id
 */
function showMenuJasper(id) {
	var depObj = $("#"+tabId+ " #"+id+"");
	var cityOffset = {"top":15,"left":0} ;
	$("#"+tabId+" #menuContent").css({left:cityOffset.left + "px", top:cityOffset.top + depObj.outerHeight() + "px"}).slideDown("fast");
	$("body").bind("mousedown", onBodyDownJasper);
}

function onBodyDownJasper(event) {
	if (!(event.target.id == "menuBtn" || event.target.id == "depName" || event.target.id == "wardName" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
		hideMenuJasper();
	}
}

function hideMenuJasper() {
	$("#"+tabId+" #menuContent").fadeOut("fast");
	$("body").unbind("mousedown", onBodyDownJasper);
}

/**
 * 根据病区设置
 * @param ward
 */
function loadTabByConfig(ward){
	var role = $('#roleName_id').val();
	var deps = $('#deps_id').val();
	var prefix = "yz" ;
	if(role == "医保") {
        prefix = "yb" ;
    }
	$("#"+tabId+" #reportGroup ul").empty() ;
	$("#"+tabId+" #reportGroup .tab-content").empty() ;
	// 
	var strl = '' ;
	var strd = '' ;
	// 各层的div
	strl+='<li role="presentation" class="active"><a href="#'+prefix+'Hosp" role="tab" data-toggle="tab">全院</a></li>'
	// 全院
	strd+='<div role="tabpanel" class="tab-pane active" id="'+prefix+'Hosp">' ;
	strd+='	<div class="col-xs-12" style="padding-bottom: 10px;">' ;
	strd+='		<div id="'+prefix+'HospDiv" style="overflow:auto; width:100%; height:460px; border:2px solid #b7bec2" ></div>' ;
	strd+='	</div>' ;
	strd+='</div>' ;
	
	if(commonLayerConfig.length>=4 && commonLayerConfig[0] == "1" ) {
		strl+='<li role="presentation"><a href="#'+prefix+'Depgroup" role="tab" data-toggle="tab">科室组</a></li>' ;
		// 科室组
		strd+='<div role="tabpanel" class="tab-pane" id="'+prefix+'Depgroup">' ;
		strd+='	<div class="col-xs-12" style="padding-bottom: 10px;">' ;
		strd+='		<div id="'+prefix+'DepgroupDiv" style="overflow:auto; width:100%; height:460px; border:2px solid #b7bec2" ></div>' ;
		strd+='	</div>' ;
		strd+='</div>' ;
	}
	if(commonLayerConfig.length>=4 && commonLayerConfig[1] == "1" ) {
		strl+='<li role="presentation"><a href="#'+prefix+'Dep" role="tab" data-toggle="tab">科室</a></li>' ;
		// 科室
		strd+='<div role="tabpanel" class="tab-pane" id="'+prefix+'Dep">' ;
		strd+='	<div class="col-xs-12" style="padding-bottom: 10px;">' ;
		strd+='		<div id="'+prefix+'DepDiv" style="overflow:auto; width:100%; height:460px; border:2px solid #b7bec2" ></div>' ;
		strd+='	</div>' ;
		strd+='</div>' ;
	}
	if(commonLayerConfig.length>=4 && commonLayerConfig[2] == "1" ) {
		strl+='<li role="presentation"><a href="#'+prefix+'Ward" role="tab" data-toggle="tab">病区</a></li>' ;
		// 病区 
		strd+='<div role="tabpanel" class="tab-pane" id="'+prefix+'Ward">' ;
		strd+='	<div class="col-xs-12" style="padding-bottom: 10px;">' ;
		strd+='		<div id="'+prefix+'WardDiv" style="overflow:auto; width:100%; height:460px; border:2px solid #b7bec2" ></div>' ;
		strd+='	</div>' ;
		strd+='</div>' ;
	}
    if(doctorSetConfig.length>=4 && doctorSetConfig[1] == "1" ) {
		strl+='<li role="presentation"><a href="#'+prefix+'Pargroup" role="tab" data-toggle="tab">主诊组</a></li>' ;
		// 主诊组
		strd+='<div role="tabpanel" class="tab-pane" id="'+prefix+'Pargroup">' ;
		strd+='	<div class="col-xs-12" style="padding-bottom: 10px;">' ;
		strd+='		<div id="'+prefix+'PargroupDiv" style="overflow:auto; width:100%; height:460px; border:2px solid #b7bec2" ></div>' ;
		strd+='	</div>' ;
		strd+='</div>' ;
	}
	$("#"+tabId+" #reportGroup ul").html(strl) ;
	$("#"+tabId+" #reportGroup .tab-content").html(strd) ;
}
